package fr.ece.ing4.si.stopwatch;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class StopWatch extends JFrame implements ActionListener {

	private static final long serialVersionUID = -8703843689450789725L;
	private boolean running;
	private boolean reset;
	JButton startStopButton;
	JButton ResetButton;
	JLabel timeLabel;
	Counter counter;
	Thread thread;
	private int count;

	@Override
	protected void frameInit() {
		super.frameInit();
		getContentPane().setLayout(new FlowLayout());
		startStopButton = new JButton();
		ResetButton = new JButton();
		timeLabel = new JLabel();
		startStopButton.setText("Start");
		ResetButton.setText("Reset");
		timeLabel.setText("0");
		
		counter = new Counter();
		thread = new Thread(counter);
		thread.start();
		
		getContentPane().add(startStopButton);
		getContentPane().add(ResetButton);
		getContentPane().add(timeLabel);
		startStopButton.addActionListener(this);
		ResetButton.addActionListener(new Reset());
	}

	public void actionPerformed(final ActionEvent event) {
		if (running)
			stopCounting();
		else
			startCounting();
	}

	private void startCounting() {
		startStopButton.setText("Stop");
		running = true;
	}

	private void stopCounting() {
		running = false;
		startStopButton.setText("Start");
		if(count>0)
			startStopButton.setText("Resume");
	}
	
	private class Reset implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			reset=true;
			
		}
		
	}
	private class Counter implements Runnable{

		@Override
		public void run() {
			count=0;
			while(true){
				if(running){
						count++;
						timeLabel.setText(String.format("%d", count));
						try {
							Thread.sleep(1000);
						} catch (InterruptedException ex) {
							throw new RuntimeException(ex);
						}
				}
				if(reset){
					count=0;
					timeLabel.setText(String.format("%d", count));
					reset=false;
					if(!running)
					startStopButton.setText("Start");
				}
			}
		}
	}
	
}


